﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wjtour.Common;

namespace Wjtour.BLL
{
    public abstract class base_dll
    {
        private DbHelper _helper;
        public base_dll()
        {
            _helper = new DbHelper();
        }

        public base_dll(string instanceName)
        {
            _helper = new DbHelper(instanceName);
        }

        /// <summary>
        /// 获取数据访问实例
        /// </summary>
        protected DbHelper DbAccess
        {
            get { return _helper; }
        }

        public virtual IEnumerable<T> GetAll<T>(string sql)
             where T : new()
        {
            return DbAccess.GetObjects<T>(sql);
        }

        protected PaginationData<T> GetPaginationData<T>(string sql, int page = 0, int pagesize = 20)
            where T : new()
        {
            Wjtour.Common.PagnationRequest pager = new PagnationRequest();
            IEnumerable<T> list = DbAccess.GetObjects<T>(sql);

            if (pagesize <= 0) pagesize = 20;
            pager.PageSize = pagesize;
            pager.TotalPages = list.Count() % pager.PageSize == 0 ? list.Count() / pager.PageSize : (list.Count() / pager.PageSize + 1);
            pager.TotalRecords = list.Count();
            if (page < 0) page = 0;
            if (page >= pager.TotalPages) page = pager.TotalPages;
            pager.CurrentPageIndex = page;

            PaginationData<T> data = new PaginationData<T>
            {
                Datas = list.Skip(pager.PageSize * pager.CurrentPageIndex).Take(pager.PageSize).ToList(),
                Pager = pager
            };
            return data;
        }

        public bool ExecuteSQL(string sql)
        {
            return DbAccess.ExecuteNonQuery(sql) > 0;
        }
    }
}
